package com.yixun.lbx.controller.company;

import com.yixun.controller.BaseController;
import com.yixun.lbx.entity.YxProCompany;
import com.yixun.lbx.entity.YxProCompanyStaff;
import com.yixun.lbx.service.CompanyService;
import com.yixun.lbx.service.CompanyStaffService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.util.annotation.Nullable;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/*
 * 企业员工 控制器
 * */
@RestController
@RequestMapping("/cs")
public class CompanyStaffController extends BaseController {
    @Value("${wisdom_bee.upload}")
    public  String WISDOM_BEE_UPLOAD;
    private final CompanyStaffService companyStaffService;
    private final CompanyService companyService;
    
    public CompanyStaffController(CompanyStaffService companyStaffService, CompanyService companyService) {
        this.companyStaffService = companyStaffService;
        this.companyService = companyService;
    }
    
    /**
     * @param map todo
     * @return java.lang.Integer
     * @apiNote addCompanyStaff 增加企业员工
     */
    @PostMapping("/addCs")
    public Integer addCompanyStaff(@RequestBody HashMap<String, Object> map) {
        String user_name = this.getSessionUser().getUser_name();
        YxProCompany company = new YxProCompany();
        company.setCode(user_name);
        Long qyId = companyService.getCompanyByIdOrNameOrCode(company).getQyId();
        map.put("qyId", qyId);
        map.put("staffType", 1);
        map.put("addUser", this.getSessionUser().getUser_id());
        return companyStaffService.addCompanyStaff(map);
        
    }
    
    /**
     * @param map todo
     * @return java.lang.Integer
     * @apiNote updateCompanyStaff 更新企业员工
     */
    @PostMapping("/updateCs")
    public Integer updateCompanyStaff(@RequestBody HashMap<String, Object> map) {
        System.out.println(map);
        map.put("updateUser", this.getSessionUser().getUser_id());
        if (map.get("imgUrl")!=null){
            String id = (String) map.get("id");
            YxProCompanyStaff one = companyStaffService.getOneById(id);
            String url =  one.getImgUrl();
            companyStaffService.deleteFile(url);
        }
        return companyStaffService.updateCompanyStaff(map);
        
    }
    
    /**
     * @param map 企业员工ID
     * @return java.lang.Integer
     * @apiNote deleteCompanyStaff 删除企业员工
     */
    @PostMapping("/deleteCompanyStaff")
    public Integer deleteCompanyStaff(@RequestBody HashMap<String, Object> map) {
        String[] ids = map.get("id").toString().split(",");
        map.put("ids", ids);
        map.put("updateUser", this.getSessionUser().getUser_id());
        return companyStaffService.deleteCompanyStaff(map);
    }
    
    /**
     * @param companyStaff todo
     * @return java.util.List<com.yixun.lbx.entity.YxProCompanyStaff>
     * @apiNote findCompanyStaffByAngs 通过相关参数查询企业员工
     */
    @GetMapping("/findCompanyStaffByAngs")
    public List<YxProCompanyStaff> findCompanyStaffByAngs(YxProCompanyStaff companyStaff) {
        return companyStaffService.findCompanyStaffByAngs(companyStaff);
    }
    
    /**
     * @param map todo
     * @return java.util.HashMap<java.lang.String, java.lang.Object>
     * @apiNote getListByPage
     */
    @RequestMapping("/getListByPage")
    public HashMap<String, Object> getListByPage(@RequestBody HashMap<String, String> map) {
        String qyCode = this.getSessionUser().getUser_name();
        map.put("code", qyCode);
        map.put("qyId", String.valueOf(getQyId()));
        Integer companyCount = companyStaffService.csCount(map);
        List<YxProCompanyStaff> companies = companyStaffService.getListByPage(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("companyCount", companyCount);
        hashMap.put("companies", companies);
        return hashMap;
    }
    
    /**
     * @param map todo
     * @return java.util.HashMap<java.lang.String, java.lang.Object>
     * @apiNote getSearchListByPage 搜索
     */
    @RequestMapping("/getSearchListByPage")
    public HashMap<String, Object> getSearchListByPage(@RequestBody HashMap<String, String> map) {
        HashMap<String, Object> hashMap = new HashMap<>();
        map.put("qyId", String.valueOf(this.getQyId()));
        List<YxProCompanyStaff> companies = companyStaffService.getSearchListByPage(map);
        hashMap.put("companies", companies);
        hashMap.put("count", companies.size());
        return hashMap;
    }
    
    private Long getQyId() {
        YxProCompany yxProCompany = new YxProCompany();
        yxProCompany.setCode(this.getSessionUser().getUser_name());
        YxProCompany company = companyService.getCompanyByIdOrNameOrCode(yxProCompany);
        if (company != null) {
            return company.getQyId();
        } else {
            return 0L;
        }
    }
    
    /**
     * @param pics     图片
     * @param report   报告
     * @param noSubmit 不上传的 过滤
     * @return java.util.HashMap<java.lang.String, java.lang.String>
     * @apiNote uploadPic 上传控制器
     */
    @RequestMapping("/uploadPic")
    public HashMap<String, String> uploadPic(HttpServletRequest request, @RequestParam("pics") MultipartFile[] pics, @RequestParam("report") @Nullable MultipartFile report, @RequestParam("noSubmit") @Nullable String noSubmit) {
        HashMap<String, String> map = new HashMap<>();
        StringBuilder imgUrl = new StringBuilder();
        String[] noSubmits = new String[0];
        if (noSubmit != null) {
            noSubmits = noSubmit.split(",");
        }
        String ext;
        loop:
        for (MultipartFile pic : pics) {
            if (pic.isEmpty()) {
                continue;
            }
            String filename = pic.getOriginalFilename();
            for (String submit : noSubmits) {
                if (submit.equals(filename)) {
                    continue loop;
                }
            }
            assert filename != null;
            if (filename.contains(".")) {
                ext = filename.substring(filename.lastIndexOf("."));
            } else {
                ext = "";
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String nfileName = uuid + ext;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(new Date());
            String[] s = date.split(" ");
            String filepath = WISDOM_BEE_UPLOAD + s[0] + "/";
            File file = new File(filepath);
            File targetFile = new File(file, nfileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                pic.transferTo(targetFile);
                imgUrl.append("/file/").append(s[0]).append("/").append(nfileName).append(",");
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        if (report != null && !report.isEmpty()) {
            String reportname = report.getOriginalFilename();
            assert reportname != null;
            if (reportname.contains(".")) {
                ext = reportname.substring(reportname.lastIndexOf("."));
            } else {
                ext = "";
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String nfileName = uuid + ext;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format.format(new Date());
            String[] s = date.split(" ");
            String filepath = WISDOM_BEE_UPLOAD + s[0] + "/";
            File file = new File(filepath);
            File targetFile = new File(file, nfileName);
            if (!file.exists()) {
                targetFile.mkdirs();
            }
            try {
                report.transferTo(targetFile);
                map.put("report", "/file/" + s[0] + "/" + nfileName);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        if (!String.valueOf(imgUrl).equals("") && String.valueOf(imgUrl).length() > 0) {
            map.put("photo", String.valueOf(imgUrl).substring(0, String.valueOf(imgUrl).length() - 1));
        }
        return map;
    }
    
}
